package com.zhongdaima.netty.analysis.part0.netty.nio;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * 欢迎关注公众号“种代码“，获取博主微信深入交流
 *
 * @author wangjianxin
 */
public class HelloNettyClient {
    private static final int CLIENTS = 2;
    private static final EventLoopGroup EVENT_LOOP_GROUP = new NioEventLoopGroup(1);

    public static void main(String[] args) throws InterruptedException {
        //用来保存两个客户端
        Channel[] clients = new Channel[CLIENTS];
        for (int i = 0; i < CLIENTS; i++) {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class)
                    .group(EVENT_LOOP_GROUP)
                    .handler(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            byte[] bytes = new byte[((ByteBuf) msg).readableBytes()];
                            ((ByteBuf) msg).readBytes(bytes);
                            //打印服务端返回数据
                            System.out.println(new String(bytes));
                        }
                    });
            //连接8000端口
            clients[i] = bootstrap.connect(new InetSocketAddress(8000)).sync().channel();
        }
        while (true) {
            for (int i = 0; i < clients.length; i++) {
                //循环向服务端发送“zhongdaima" + 客户端编号
                clients[i].writeAndFlush(Unpooled.wrappedBuffer(("zhongdaima" + i).getBytes()));
            }
            Thread.sleep(1000);
        }
    }
}
